<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.year"
        :placeholder="$t('table.year')"
        clearable
        class="filter-item"
        style="width: 130px"
        @change="yearChange"
      >
        <el-option v-for="item in calendarYearOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select
        v-model="listQuery.month"
        :placeholder="$t('table.month')"
        clearable
        class="filter-item"
        style="width: 130px"
        @change="monthChange"
      >
        <el-option v-for="item in calendarMonthOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        {{ $t('table.export') }}
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        {{ $t('table.reviewer') }}
      </el-checkbox>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('table.name')" prop="name" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.insurance')"
        prop="insurance"
        sortable="custom"
        align="center"
        min-width="90"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span class="link-type" @click="handleInsurance(row)">{{ row.insurance }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.fund')"
        prop="fund"
        sortable="custom"
        align="center"
        min-width="90"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.fund }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.allowance')"
        prop="allowance"
        sortable="custom"
        align="center"
        min-width="100"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span class="link-type" @click="handleAllowance(row)">{{ row.allowance }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.charge')"
        prop="charge"
        sortable="custom"
        align="center"
        min-width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span class="link-type" @click="handleCharge(row)">{{ row.charge }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.tax')"
        prop="tax"
        sortable="custom"
        align="center"
        min-width="100"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.tax }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.payable')"
        prop="payable"
        sortable="custom"
        align="center"
        min-width="100"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.payable }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.payroll')"
        prop="payroll"
        sortable="custom"
        align="center"
        min-width="100"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.payroll }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showReviewer" :label="$t('table.reviewer')" width="100" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" min-width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button type="primary" size="mini" @click="handleDetail(row)">
            {{ $t('table.detail') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!--社保-->
    <el-dialog :visible.sync="dialogInsuranceVisible" :title="$t('table.insurance')">
      <el-table :data="insuranceData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="endowment" :label="$t('table.endowment')" />
        <el-table-column prop="medical" :label="$t('table.medical')" />
        <el-table-column prop="unemployment" :label="$t('table.unemployment')" />
        <el-table-column prop="injury" :label="$t('table.injury')" />
        <el-table-column prop="maternity" :label="$t('table.maternity')" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogInsuranceVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <!--补贴-->
    <el-dialog :visible.sync="dialogAllowanceVisible" :title="$t('table.allowance')">
      <el-table :data="allowanceData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="overtime" :label="$t('table.overtime')" />
        <el-table-column prop="meal" :label="$t('table.meal')" />
        <el-table-column prop="transport" :label="$t('table.transport')" />
        <el-table-column prop="housing" :label="$t('table.housing')" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogAllowanceVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <!--扣款-->
    <el-dialog :visible.sync="dialogChargeVisible" :title="$t('table.charge')">
      <el-table :data="chargeData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="absent" :label="$t('table.absent')" />
        <el-table-column prop="late" :label="$t('table.late')" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogChargeVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import {
  getAllowanceList,
  getChargeList,
  getInsuranceList,
  getSalaryListById,
  getSalaryMonthByUserId,
  getSalaryYearByUserId
} from '@/api/user'
import { parseTime } from '@/utils' // secondary package based on el-pagination

export default {
  name: 'PersonalDetail',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        userId: 0,
        page: 1,
        limit: 20,
        year: undefined,
        month: undefined,
        sort: '+id'
      },
      calendarMonthOptions: [{ key: 1, display_nam: '1 月' }],
      calendarYearOptions: [{ key: 2020, display_nam: '2020 年' }],
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      row: {
        id: 1,
        name: '',
        insurance: 0.00,
        fund: 0.00,
        allowance: 0.00,
        charge: 0.00,
        tax: 0.00,
        payable: 0.00,
        payroll: 0.00,
        reviewer: '',
        date: ''
      },
      dialogInsuranceVisible: false,
      insuranceData: null,
      dialogAllowanceVisible: false,
      allowanceData: null,
      dialogChargeVisible: false,
      chargeData: null,
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    const userId = this.$store.getters.id
    getSalaryYearByUserId(userId).then(response => {
      // 单纯的 Array 返回一个对象数组
      const data = response.data
      if (data !== null) {
        for (let i = 0; i < data.length; i++) {
          const obj = { key: 0, display_name: '' }
          obj.key = data[i]
          obj.display_name = data[i] + '年'
          this.calendarYearOptions[i] = obj
        }
      }
    })
    getSalaryMonthByUserId(userId).then(response => {
      // 单纯的 Array 返回一个对象数组
      const data = response.data
      if (data !== null) {
        for (let i = 0; i < data.length; i++) {
          const obj = { key: 0, display_name: '' }
          obj.key = data[i]
          obj.display_name = data[i] + '月'
          this.calendarMonthOptions[i] = obj
        }
      }
    })
  },
  methods: {
    // this.getList()
    getList() {
      this.listLoading = true
      this.listQuery.userId = this.$store.getters.id
      getSalaryListById(this.listQuery).then(response => {
        const data = response.data
        this.list = data.records
        this.total = data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleFilter() {
      this.listQuery.page = 1
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    yearChange(val) {
      console.log(val)
      this.listQuery.year = val
      this.getList()
    },
    monthChange(val) {
      console.log(val)
      this.listQuery.month = val
      this.getList()
    },
    handleInsurance(row) {
      this.dialogInsuranceVisible = true
      getInsuranceList(row.id).then(response => {
        const data = response.data
        const arr = []
        arr.push(data)
        this.insuranceData = arr
        console.log(arr)
      })
    },
    handleAllowance(row) {
      this.dialogAllowanceVisible = true
      getAllowanceList(row.id).then(response => {
        const data = response.data
        const arr = []
        arr.push(data)
        this.allowanceData = arr
        console.log(arr)
      })
    },
    handleCharge(row) {
      this.dialogChargeVisible = true
      getChargeList(row.id).then(response => {
        const data = response.data
        const arr = []
        arr.push(data)
        this.chargeData = arr
        console.log(arr)
      })
    },
    handleDetail(row) {
      this.$router.push({
        path: '/salary/detail',
        // 传递的是薪资 SalaryId
        query: {
          id: row.id
        }
      })
      // 使用时则用：this.$route.query.id
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['姓名', '社会保险', '公积金', '补贴', '扣除款', '个人所得税', '应发金额', '实发金额', '时间']
        const filterVal = ['name', 'insurance', 'fund', 'allowance', 'charge', 'tax', 'payable', 'payroll', 'date']
        const list = this.list
        console.log(list)
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'salary-list',
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
